package com.itmayiedu.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: zuul过滤器拦截token
 * @author: liucancan
 * @create: 2018-11-26 12:45
 **/
// @Component
public class TokenFilter extends ZuulFilter {

    @Value("${server.port}")
    private String serverPort;

    /**
     * 定义过滤器是否生效
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 编写拦截器业务逻辑实现代码
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        // 当前上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        // 获取request对象
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        String userToken = request.getParameter("userToken");
        // 返回错误提示
        if (null == userToken) {
            // 停止请求继续执行
            context.setSendZuulResponse(false);
            context.setResponseBody("userToken is null 网关项目端口号：" + serverPort);
            context.setResponseStatusCode(401);
            return null;
        }
        return null;
    }

    /**
     * 定义过滤类型，如 per : 标识请求执行前执行
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 定义该过滤器在多个过滤器中的执行顺序
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }
}
